package com.juyu.miliao.api.handler;

import com.juyu.miliao.api.constant.DepositType;
import com.juyu.miliao.api.dao.mysql.*;
import com.juyu.miliao.api.domain.*;
import com.juyu.miliao.api.service.IntegralLevelInfoService;
import com.juyu.miliao.common.util.DoubleFormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

/**
 * @author xuanqicheng
 */
@Component
@Slf4j
public class UserInvitationIncomeDetailsHandler {

    @Autowired
    private UserInvitationBindingInfoDao userInvitationBindingInfoDao;

    @Autowired
    private UserInvitationIncomeDetailsDao userInvitationIncomeDetailsDao;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private UserWalletDao userWalletDao;

    @Autowired
    private BillDetailDao billDetailDao;

    @Autowired
    private IntegralLevelInfoService integralLevelInfoService;

    /**
     * 主播分成
     */
    private BigDecimal hostDivideInto = new BigDecimal("0.20");

    /**
     * 充值金币分成
     */
    private BigDecimal coinDivideInto = new BigDecimal("0.30");

    /**
     * 被邀请的用户是主播，赚钱的钻石分成给邀请人，
     * @param invitedUserId
     * @param recordType
     * @param diamonds
     */
    @Transactional(rollbackFor = Exception.class)
    public void incomeDiamondsDetails(long invitedUserId, int recordType, BigDecimal diamonds){

        LocalDateTime nowTime = LocalDateTime.now();

        UserInvitationBindingInfo userInvitationBindingInfo = userInvitationBindingInfoDao
                .selectUserInvitationBindingInfoByInvitedUserId(invitedUserId);

        if(userInvitationBindingInfo==null){
            log.info("用户：[{}]不是被邀请用户，赚取钻石不进行分成",invitedUserId);
            return;
        }

        User user = userInfoDao.getUserInfoById(invitedUserId);

        if(user.getIsHost()==1){
            if(userInvitationBindingInfo.getAuthenticationTime()!=null){
                LocalDateTime createTime = userInvitationBindingInfo.getAuthenticationTime();
                if(nowTime.isBefore(createTime.plusDays(180))){

                    BigDecimal bigDecimal = diamonds.multiply(hostDivideInto).setScale(2,
                            RoundingMode.HALF_UP);

                    if(bigDecimal.doubleValue()>0){
                        UserWallet userWallet = new UserWallet();
                        userWallet.setUserId(userInvitationBindingInfo.getInviteUserId());
                        userWallet.setDiamond(bigDecimal.doubleValue());
                        int flag = userWalletDao.reviseDiamond(userWallet);
                        log.info("被邀请用户:[{}],收益类型:[{}]赚钱钻石:[{}];邀请用户：[{}],分成获得钻石:[{}]",
                                invitedUserId,recordType, diamonds.doubleValue(),
                                userWallet.getUserId(),userWallet.getDiamond());
                        if(flag==1){
                            addBillInfo(userWallet,DepositType.INVITE_HOST_GIVE_DIAMONDS,0);
                            addUserInvitationIncomeDetailsInfo(recordType, userInvitationBindingInfo, bigDecimal,1,1);
                        }
                    }
                }
            }else{
                log.info("被邀请用户的authenticationTime为空userId=[{}]",invitedUserId);
            }
        }

    }


    /**
     * 充值金币分成
     * @param invitedUserId
     * @param coinNumber
     */
    @Transactional(rollbackFor = Exception.class)
    public void incomeRechargeDetails(long invitedUserId,BigDecimal coinNumber) {

        LocalDateTime nowTime = LocalDateTime.now();

        UserInvitationBindingInfo userInvitationBindingInfo = userInvitationBindingInfoDao
                .selectUserInvitationBindingInfoByInvitedUserId(invitedUserId);

        if (userInvitationBindingInfo == null) {
            log.info("用户：[{}]不是被邀请用户，赚取钻石不进行分成", invitedUserId);
            return;
        }

        int registrationType = 0;
        User user = userInfoDao.getUserInfoById(invitedUserId);
        if (user.getIsHost() == 1) {
            registrationType = 1;
        }

        LocalDateTime createTime = userInvitationBindingInfo.getCreateTime();
        if (nowTime.isBefore(createTime.plusDays(180))) {

//            BigDecimal diamondConversionRate =integralLevelInfoService
//                    .getDiamondConversionRate(userInvitationBindingInfo.getInviteUserId());

            BigDecimal incomCoin = coinNumber.multiply(coinDivideInto)
                    .setScale(2,RoundingMode.HALF_UP);

//            BigDecimal bigDecimal = incomCoin.multiply(diamondConversionRate)
//                    .setScale(2, RoundingMode.HALF_UP);

            if(incomCoin.doubleValue()>0){

                UserWallet userWallet = new UserWallet();
                userWallet.setUserId(userInvitationBindingInfo.getInviteUserId());
                userWallet.setDiamond(incomCoin.doubleValue());
                int flag = userWalletDao.reviseDiamond(userWallet);
                log.info("被邀请用户:[{}],充值金币:[{}];邀请用户：[{}],获得分成金币:[{}]，转化钻石：[{}],金币转钻石的转化率：[{}]",
                        invitedUserId,coinNumber.intValue(),userInvitationBindingInfo.getInviteUserId(),
                        incomCoin.intValue(),incomCoin.doubleValue(),"100%");
                if(flag==1){
                    addBillInfo(userWallet,DepositType.INVITE_FRIENDS_GIVE_DIAMONDS,100);
                    addUserInvitationIncomeDetailsInfo(DepositType.PAY_VIP_ADD_BEANS.getCode(),
                            userInvitationBindingInfo,incomCoin,registrationType,0);
                }
            }
        }
    }


    /**
     * 生成分享钻石
     * @param userWallet
     * @param ratio  转化比例
     */
    private void addBillInfo(UserWallet userWallet,DepositType depositType,double ratio) {
        BillDetailDeposit billDetailDeposit = new BillDetailDeposit();
        billDetailDeposit.setRecordType(depositType.getCode());
        // 赚取钻石用户id
        billDetailDeposit.setInUserId(userWallet.getUserId());
        // 赚取钻石数
        billDetailDeposit.setDiamond(userWallet.getDiamond());
        billDetailDeposit.setRatio(ratio);
        billDetailDao.insertBillDetailDeposit(billDetailDeposit);
    }

    /**
     * 添加邀请好友明细
     * @param recordType 消费类型
     * @param userInvitationBindingInfo 绑定关系信息
     * @param bigDecimal 分成钻石
     * @param registrationType 注册类型 0：用户，1：主播
     * @param detailType 明细类型：0：邀请用户赚取类型，1：邀请主播赚钱类型
     */
    private void addUserInvitationIncomeDetailsInfo(int recordType, UserInvitationBindingInfo userInvitationBindingInfo,
                                                    BigDecimal bigDecimal,int registrationType,int detailType) {
        UserInvitationIncomeDetails details = new UserInvitationIncomeDetails();
        details.setInviteUserId(userInvitationBindingInfo.getInviteUserId());
        details.setInvitedUserId(userInvitationBindingInfo.getInvitedUserId());
        details.setDiamonds(bigDecimal);
        details.setRecordType(recordType);
        details.setRegistrationType(registrationType);
        details.setRegistrationTime(userInvitationBindingInfo.getCreateTime());
        details.setDetailType(detailType);
        userInvitationIncomeDetailsDao.insert(details);
    }


}
